package com.itheima.handler;


import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handlerException(SQLIntegrityConstraintViolationException e){
        String errorMessage = e.getMessage();
        log.error(errorMessage);
        String[] split = errorMessage.split("'");
        if("idx_username".equals(split[3])){
            return R.error("用户名已存在");
        }
        return null;
    }

}
